#include <REGX52.H>
#include "LCD1602.h"
#include "KeyPro.h"
#include "Delay.h"
#include "Timer0.h"
#include "AT24C02.h"
#include "DS18B20.h"

float T,TShow;
char TLow,THigh;
unsigned char KeyNum;
void main()
{
	LCD_Init();
	Timer0_Init();
	LCD_ShowString(1,1,"T:");
	LCD_ShowString(2,1,"TH:");
	LCD_ShowString(2,9,"TL:");
	while(1)
	{
		//温度读取及显示
		DS18B20_ConvertT();
		T = DS18B20_ReadT();
		if(T<0)
		{
	    LCD_ShowString(1,3,"-");	
			TShow = -T;
		}
		else
		{
			TShow = T;			
	    LCD_ShowString(1,3,"+");				
		}
		LCD_ShowNum(1,4,TShow,3);
	  LCD_ShowString(1,7,".");				
		LCD_ShowNum(1,8,(unsigned long)(TShow*100)%100,2);		
		
		//阈值判读及显示
		KeyNum = Key();
		THigh = AT24C02_ReadByte(0);
		TLow = AT24C02_ReadByte(1);
		if(THigh>125 || TLow<-55 || THigh<=TLow)
		{
			THigh = 25;
			TLow = 0;
		}
		if(KeyNum)
		{
			if(KeyNum==1)
			{
				THigh++;
				if(THigh>125){THigh=125;}//最大可测温度
			}	
			if(KeyNum==2)
			{
				THigh--;
				if(THigh<=TLow){THigh++;}
			}	
			if(KeyNum==3)
			{
				TLow++;
				if(TLow>=THigh){TLow--;}
			}	
			if(KeyNum==4)
			{
				TLow--;
				if(TLow<-55){TLow=-55;}//最低可测温度
			}	
			AT24C02_WriteByte(0,THigh);
			AT24C02_WriteByte(1,TLow);		
		}
		LCD_ShowSignedNum(2,4,THigh,3);
		LCD_ShowSignedNum(2,12,TLow,3);	
		
		if(T>THigh)
		{
			LCD_ShowString(1,13,"OV:H");	
		}
		else if(T<TLow)
		{
			LCD_ShowString(1,13,"OV:L");			
		}
		else
		{
			LCD_ShowString(1,13,"     ");			
		}
	}
}


//因单总线操作时间量级也在几微妙，加中断会使单总线操作出错
//所以在单总线操作时要关闭中断
void Timer0_Routine() interrupt 1
{
	static unsigned int T0Count;
	TL0 = 0x18;				//设置定时初始值
	TH0 = 0xFC;				//设置定时初始值
	T0Count++;
	if(T0Count>=20)
	{
		T0Count = 0;
		Key_Loop();
	}
}